package com.example.bluetoothclicker.bluetoothreceiver

import android.bluetooth.BluetoothDevice
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.example.bluetoothclicker.func.BluetoothConnectionManager

class BluetoothEventHandler(private val context: Context) : BluetoothObserver {

    override fun onDeviceDiscovered(device: BluetoothDevice) {
        Logger.d("发现设备: ${device.name} (${device.address})")
    }

    override fun onPairingCompleted(device: BluetoothDevice) {
        Logger.d("配对完成: ${device.name} (${device.address})")
    }

    override fun onConnectionStateChanged(device: BluetoothDevice, isConnected: Boolean) {
        val status = if (isConnected) "已连接" else "已断开连接"
        Logger.d("${device.name} (${device.address}) $status")
        showToast("test1111")
        if (isConnected) {
            if (BluetoothConnectionManager.isConnectedAsServe()||BluetoothConnectionManager.isConnectedAsClient()) {
                BluetoothConnectionManager.connectToServer(
                    device = device,
                    onConnected = { message ->
                        showToast(message)
                    },
                    onError = { error ->
                        showToast(error)
                    }
                )
            }
        } else {
            if (BluetoothConnectionManager.isConnectedAsServe())
            {
                BluetoothConnectionManager.closeClientOnServe(device.address)
            }else if (BluetoothConnectionManager.isConnectedAsClient()){
                if(BluetoothConnectionManager.getClient()?.getServerAddress()==device.address)
                {
                    BluetoothConnectionManager.disconnectFromServer()
                }
            }
        }
    }

    private fun showToast(message: String) {
        Handler(Looper.getMainLooper()).post {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }
    }
}

object Logger {
    private const val TAG = "BluetoothEventHandler"

    fun d(message: String) {
        Log.d(TAG, message)
    }

    fun e(message: String, throwable: Throwable? = null) {
        Log.e(TAG, message, throwable)
    }
}
